package com.feng.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.feng.chat.dto.Result;
import com.feng.chat.entity.SplitUpload;
import com.feng.chat.entity.TalkRecordsFile;
import com.feng.chat.mapper.SplitUploadMapper;
import com.feng.chat.mapper.TalkRecordsFileMapper;
import com.feng.chat.service.ISplitUploadService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 文件拆分上传 服务实现类
 * </p>
 *
 * @author dyf
 * @since 2022-05-31
 */
@Service
public class SplitUploadServiceImpl extends ServiceImpl<SplitUploadMapper, SplitUpload> implements ISplitUploadService {

    @Autowired
    private SplitUploadMapper splitUploadMapper;

    /**
     * 获取拆分文件信息
     *
     * @param file_name
     * @param file_size
     * @return
     */
    @Override
    public Result multipartInitiate(Integer uid, String file_name, Long file_size) {
        String path = "E:\\Desktop\\案例\\javaweb案例\\MyChat\\resource\\file\\" + file_name;

        long split_size = 2097152;
        int split_num = (int) Math.ceil(file_size * 1.0 / split_size);
        String upload_id = UUID.randomUUID().toString().replaceAll("-", "");

        SplitUpload splitUpload = new SplitUpload();
        splitUpload.setType(1);
        splitUpload.setDrive(1);
        splitUpload.setUserId(uid);
        splitUpload.setUploadId(upload_id);
        splitUpload.setOriginalName(file_name);
        splitUpload.setSplitIndex(split_num);
        splitUpload.setSplitNum(split_num);
        splitUpload.setPath(path);
        splitUpload.setFileExt(file_name.substring(file_name.lastIndexOf(".") + 1));
        splitUpload.setFileSize(file_size);

        splitUploadMapper.insert(splitUpload);

        Map<String, Object> map = new HashMap<>();
        map.put("split_size", split_size);
        map.put("upload_id", upload_id);
        return Result.success(map);
    }

    /**
     * 文件拆分上传
     *
     * @param uid
     * @param file
     * @param upload_id
     * @param split_index
     * @param split_num
     * @return
     */
    @Override
    public Result multipart(Integer uid, MultipartFile file, String upload_id, Integer split_index, Integer split_num) {
        String splitPath = "E:\\Desktop\\案例\\javaweb案例\\MyChat\\resource\\splitFile\\" + split_index + ".tmp";
        File splitFile = new File(splitPath);
        if (!splitFile.getParentFile().exists()) {
            splitFile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(splitFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        SplitUpload splitUpload = new SplitUpload();
        splitUpload.setType(2);
        splitUpload.setDrive(1);
        splitUpload.setUserId(uid);
        splitUpload.setUploadId(upload_id);
        splitUpload.setOriginalName(split_index + ".tmp");
        splitUpload.setSplitIndex(split_index);
        splitUpload.setSplitNum(split_num);
        splitUpload.setPath(splitPath);
        splitUpload.setFileExt("tmp");
        splitUpload.setFileSize(file.getSize());

        splitUploadMapper.insert(splitUpload);


        HashMap<String, Object> map = new HashMap<>();
        if (split_index == split_num - 1) {
            QueryWrapper<SplitUpload> splitUploadQueryWrapper = new QueryWrapper<>();
            splitUploadQueryWrapper.eq("upload_id", upload_id).eq("type", 1).eq("is_delete", 0).eq("user_id", uid);
            SplitUpload mergeUpload = splitUploadMapper.selectOne(splitUploadQueryWrapper);

            File mergeFile = new File(mergeUpload.getPath());
            if (!mergeFile.getParentFile().exists()) {
                mergeFile.getParentFile().mkdirs();
            }
            try {
                FileOutputStream fileOutputStream = new FileOutputStream(mergeFile);
                for (int i = 0; i < split_num; i++) { //合并拆分文件
                    File tmpFile = new File("E:\\Desktop\\案例\\javaweb案例\\MyChat\\resource\\splitFile\\" + i + ".tmp");
                    FileInputStream fileInputStream = new FileInputStream(tmpFile);
                    byte[] bytes = new byte[1024];
                    int len = 0;
                    while ((len = fileInputStream.read(bytes)) != -1) {
                        fileOutputStream.write(bytes, 0, len);
                    }
                    fileInputStream.close();

                    //删除临时文件
                    UpdateWrapper<SplitUpload> splitUploadUpdateWrapper = new UpdateWrapper<>();
                    splitUploadUpdateWrapper.eq("upload_id", upload_id).eq("type", 2).eq("is_delete", 0).eq("user_id", uid).set("is_delete",1);
                    splitUploadMapper.update(null,splitUploadUpdateWrapper);

                    if (tmpFile.isFile() && tmpFile.exists()) {
                        tmpFile.delete();
                    }
                }
                fileOutputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            map.put("is_merge", true);
            map.put("upload_id", upload_id);
        } else {
            map.put("is_merge", false);
        }
        return Result.success(map);
    }
}
